<?php

namespace app\api\controller;

use app\admin\model\product\Category;
use app\admin\model\product\Listo;
use app\admin\model\product\Lists;
use app\admin\model\product\Order;
use app\admin\model\product\Sku;
use app\common\controller\Payment;
use think\Db;
use think\Exception;
use think\Request;
use app\common\controller\Api;

class Productorder extends Api
{
    protected static $model = null;
    protected $noNeedLogin = ['logisticsInfo', 'notify'];
    protected $noNeedRight = '*';
    protected static $totalList = 15;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new Order();
    }

    /**
     * 提交订单
     */
    public function createorder()
    {
        if (!request()->isPost()) {
            $this->error('非法操作！');
        }
        $user_id = $this->auth->id;
        $user = \app\admin\model\User::find($user_id);
        $tag = input('tag');
        $message = input('message');
        $paytype = input('paytype');//1为微信，2为支付宝，3为货到付款
        $transtype = input('transtype');
        if (!$tag) {
            $this->error('非法操作！');
        }
        if (!$paytype) {
            $paytype = 2;
        }
//        $password = input('password');
//        if ($uinfo['psd2'] != $password) {
//            $this->apiError('支付密码错误！');
//        }

        $orderInfo = Order::where('orderid', $tag)->find();
        if ($orderInfo) {
            $this->error('重复提交订单');
        }

        $addressid = \app\admin\model\Transport::where("status='1' and user_id='$user_id'")->value('id');
        if ($addressid <= 0) {
            $this->error('必须默认一个收货地址！');
        }

        //获取该用户购物清单中的数据
        $shoplist = Listo::where('tag', $tag)->select();

        if (!$shoplist) {
            $this->error('请先购买商品！');
        }

        $nums = 0;
        $total = 0;
        $transfee = 0;
        $mark = '';
        foreach ($shoplist as $v) {
            $productInfo = Lists::where('id', $v->product_id)->find();
//            $cmark = Category::where('id', $productInfo->category_id)->value('mark');

//            if ($mark == '') {
//                $mark = $cmark;
//            } else {
//                if ($cmark != $mark) {
//                    $this->error('一次只能购买一个种类的商品！');
//                }
//            }

            $nums += $v['num'];
            $total += $v['total'];
            $transfee += $productInfo['transfee'] * $v['num'];
        }

        $all = $total + $transfee;

        $data['addressid'] = $addressid;//收货人地址
        $data['total'] = $total;//总金额
        $data['transtype'] = $transtype;
        $data['transfee'] = $transfee;
        $data['all'] = $all;
        $data['orderid'] = $tag;//订单号
        $data['user_id'] = $user_id;//当前用户id
        $data['department_user_id'] = $user->department_user_id;
        $data['backinfo'] = '预下单';
        $data['message'] = $message;
        $data['paytype'] = $paytype;//等待发货
        $data['status'] = 0;

        Db::startTrans();
        try {
            $odata = self::$model->create($data);
            Listo::where('tag', $tag)->setField('order_id', $odata->id);
            if ($paytype == 3) {
                $ndata = [
                    'pay_time' => time(),
                    'status' => 1
                ];
                Listo::where('order_id', $odata->id)->update($ndata);
                $ndata['backinfo'] = '已下单';
                $odata->save($ndata);

                self::updateShop($odata->id);
                $all = 0;
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success("订单已生成！", [
            'order_num' => $tag,
            'total' => $all
        ]);

    }

    /**
     * 立即支付
     */
    public function pay()
    {
        $orderNum = $this->request->post('order_num');
        $paytype = $this->request->post('paytype', 'wechat');
        if (!$orderNum) {
            $this->error('关键参数缺失！');
        }

        if (!in_array($paytype, ['wechat', 'alipay'])) {
            $this->error('支付方式不存在！');
        }

        $oInfo = self::$model->where('orderid', $orderNum)->find();
        if (!$oInfo) {
            $this->error('该订单不存在！');
        }

        $data = [
            'money' => $oInfo->all,
            'order_no' => $orderNum,
            'body' => '国善医疗',
            'remark' => '国善医疗'
        ];

        if ($paytype == 'wechat') {
            $data['paytype'] = 'W06';
            $oInfo->paytype = 1;
        } else {
            $data['paytype'] = 'A02';
            $oInfo->paytype = 2;
        }

        $payMent = new Payment();
        $res = $payMent->pay($data);

        $oInfo->save();
        $this->success('订单参数为', $res);
    }

    /**
     * 查询订单详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkOrder()
    {
        $orderId = $this->request->post('order_num');
        $oInfo = self::$model->field('id,status')->where('orderid', $orderId)->find();
        if (!$oInfo) {
            $this->error('该订单不存在！');
        }

        $this->success('订单信息', $oInfo);
    }

    /**
     * 支付回调
     */
    public function notify()
    {
        $params = array();
        foreach ($_POST as $key => $val) {//动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
            $params[$key] = $val;
        }

//        $params = [
//            'cusorderid' => '2292218857102959'
//        ];
//        $params = json_decode('{"acct":"opn0buK9prs3IaJcA4QczfDvJCps","accttype":"99","appid":"00317165","bankcode":"OTHERS","chnlid":"205299480","chnltrxid":"4200002313202407315386738395","cmid":"673352229","cusid":"56349105651R6V1","cusorderid":"2241046485198548","fee":"0","initamt":"1","outtrxid":"2241046485198548","paytime":"20240731152211","sign":"FDa6lyrhezw53jeya8MieP6HvilJKY9PzQhJCK0jrqg4rzW\/PtjbuyttG5x0gT+v9TOzoLJM\/Dbdh6wyUgDSLFkxVOntA2SyFu4Q92qHgKC+caHIKiA7x+7e1S30AKRQdlYFDemwdgXqrk60+TvKGVDDAyCAGgSvB+5bZR8OOkM=","signtype":"RSA","termauthno":"OTHERS","termrefnum":"4200002313202407315386738395","termtraceno":"0","trxamt":"1","trxcode":"VSP501","trxdate":"20240731","trxid":"240731110614192865","trxreserved":"recharge","trxstatus":"0000"}', true);
//        if (count($params) < 1) {//如果参数为空,则不进行处理
//            echo "error";
//            exit();
//        }
//var_dump($params);die;
//        write_log($params, 'notify_data');
//        $vdata = [
//            'cusid' => $params['cusid'],
//            'appid' => $params['appid'],
//            'version' => 12,
//            'trxamt' => $params['trxamt'],
//            'reqsn' => $params['reqsn'],
//            'body' => $params['body'],
//            'remark' => $params['trxreserved'],
//            'returl' => $params['appid'],
//            'notify_url' => $params['appid'],
//            'charset' => 'utf-8',
//            'randomstr' => $params['appid'],
//            'signtype' => $params['appid'],
//            'sign' => $params['appid']
//        ];
//        if (Payment::ValidSign($params)) {//验签成功
        //此处进行业务逻辑处理
        write_log($params, 'notify_data');

        $oInfo = self::$model->where('orderid', $params['cusorderid'])->find();
        if (!$oInfo) {
            write_log('订单号' . $params['cusorderid'] . '的订单不存在', 'notify_error');
            echo "success";
            die;
        }

        if ($oInfo->status == 1) {
            write_log('订单号' . $params['cusorderid'] . '的订单不可充值', 'notify_error');
            echo "success";
            die;
        }

        Db::startTrans();
        try {
            /*更新状态*/
            $ndata = [
                'pay_time' => time(),
                'status' => 1
            ];
            Listo::where('order_id', $oInfo->id)->update($ndata);
            $ndata['backinfo'] = '已下单';
            $oInfo->save($ndata);

            self::updateShop($oInfo->id);

            Db::commit();
            echo "success";
        } catch (Exception $exception) {
            Db::rollback();
            write_log('订单号' . $params['cusorderid'] . '的订单报错：' . $exception->getMessage(), 'notify_error');
            echo "erro";
        }
//        } else {
//            echo "erro";
//        }
    }

    /**
     * 更新商品销量
     * @param $list
     * @throws \think\Exception
     */
    private function updateShop($orderId)
    {
        $list = Listo::where('order_id', $orderId)->select();
        foreach ($list as $k => $val) {
            Sku::where('id', $val->sku_id)->setDec('stock', $val['num']);
            Lists::where(array('id' => $val->product_id))->setInc('sell_num', $val['num']);
            Lists::where(array('id' => $val->product_id))->setDec('goods_num', $val['num']);
        }
    }

    /**
     * 订单列表
     */
    public function lists()
    {
        $pageSize = input('page_size', self::$totalList);
        $status = $this->request->post('status');
        if (!$status) {
            $status = [-1];
        } else {
            $status = explode(',', $status);
        }

        $map = [];
        if (!in_array(-1, $status)) {
            $map['status'] = ['in', $status];
        }

        $user_id = $this->auth->id;

        $orders = self::$model
            ->field("id,orderid,total,transfee,all,status,paytype,addressid,createtime")
            ->where('user_id', $user_id)
            ->where($map)
            ->order('id desc')
            ->paginate($pageSize)
            ->each(function ($item) {
                $lists = Listo::where('order_id', $item['id'])->select();
                $totalNum = 0;
                if (count($lists) > 0) {
                    foreach ($lists as &$vv) {
                        $pInfo = Lists::where('id', $vv['product_id'])->find();
//                        $vv['product_name'] = $pInfo['product_name'];
//                        $vv['parameter'] = ProductSku::where('id', $vv['parameter_id'])->value('value');

                        $attrs = $this->get_attrs($pInfo['intro']);
                        $vv['attrs'] = $attrs;
                        $vv['intro'] = $pInfo['intro'];
                        $vv['image'] = make_full_url($pInfo['image']);
                        $totalNum += $vv['num'];
                    }
                }
                $item['createtime'] = date('Y-m-d H:i:s', $item['createtime']);
                $item['total_num'] = $totalNum;
                $item['product_list'] = $lists;
            });

        $totalCount = self::$model
            ->where('user_id', $user_id)
            ->where($map)
            ->count();

        $this->success('订单列表', ['list' => $orders, 'totalCount' => $totalCount]);
    }

    /**
     * 确认订单
     */
    public function confirmOrder()
    {
        if (!request()->isPost()) {
            $this->error('非法操作！');
        }

        $id = input('id');
        $list = Listo::where('id', $id)->find();

        if (!$list) {
            $this->error('该订单不存在！');
        }

        $oInfo = self::$model->find($list['order_id']);
        if ($list['status'] != 10) {
            $this->error('该订单不可确认！');
        }

        Db::startTrans();
        try {
            $time = time();
            $list->status = 20;
            $list->backinfo = 'success';
            $list->finish_time = $time;
            $res = $list->save();

            $num = Listo::where('order_id', $list['order_id'])->where('status', 'lt', 20)->count();
            if ($num == 0) {
                $data = [
                    'backinfo' => 'success',
                    'finish_time' => $time,
                    'status' => 20
                ];
                $oInfo->save($data);

                $money = round($oInfo->total * $oInfo->rate * 0.01, 2);
                $content = '您好，运单号' . $list->tool . '的商品已被签收，分红到账' . $money . '元';
                $department_user_id = $oInfo->department_user_id;
                (new Common())->sendAppMsg($department_user_id, 'notice', '盈利消息', $content);

                $type = 'profile';
                $ndata = [
                    'user_id' => $department_user_id,
                    'type' => $type,
                    'relation_id' => $oInfo->id,
                    'content' => $content,
                    'is_read' => 0,
                ];
                \app\admin\model\Notices::create($ndata);

                $user = \app\admin\model\department\User::find($department_user_id);
                if ($user->is_leader == 0) {
                    $luser = \app\admin\model\department\User::where('department_id', $user->department_id)
                        ->where('is_leader', 1)
                        ->find();
                    if ($luser) {

                        $content = str_replace('您好，', '您好，' . $user->username . '的', $content);
                        $ndata = [
                            'user_id' => $luser->id,
                            'type' => $type,
                            'relation_id' => $oInfo->id,
                            'content' => $content,
                            'is_read' => 0,
                        ];
                        \app\admin\model\Notices::create($ndata);
                    }
                }
            }

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('签单成功');
    }

    /**
     * 删除订单
     */
    public function delOrder()
    {
        if (!request()->isPost()) {
            $this->error('非法操作！');
        }

        $id = input('id');
        $orderInfo = self::$model->where('id', $id)->find();
        if (!$orderInfo) {
            $this->error('该订单不存在！');
        }
        if ($orderInfo['status'] != 20) {
            $this->error('该订单不可删除！');
        }

        $res = self::$model->where('id', $id)->update(['status' => -2]);
        if (!$res) {
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }
}